﻿using AppDataStruct;
using ComUIControl;
using EECMISWS;
using KCommon;
using KWindow.KPageCore;
using KXmlUIControl.KControl;
using LogLib;
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace YSLPages
{
    public partial class PageApplyPassportInfo : PageControlBase
    {
        private PreApplyInfo _appInfo = null;
        private bool _bInited = false;
        private KCheckBox kCheckBoxJZ = null;
        private KCheckBox kCheckBoxHZSXCXSQ = null;
        private KCheckBox kCheckBoxHZSCSQ = null;
        private KCheckBox kCheckBoxHZHF = null;
        private KCheckBox kCheckBoxHZBF = null;
        private TextBox textBoxYXQ = null;
        private TextBox textBoxHZHM = null;
        private TextBox textBoxCYM = null;
        private TextBox textBoxXM = null;
        private TextBox textBoxCCHZHM = null;
        private TextBox textBoxQWD = null;
        private TextBox textBoxCJSY = null;
        private Button buttonOK = null;
        private Button buttonCancell = null;
        private List<KCheckBox> listHZSQLBCheckBoxs = new List<KCheckBox>();
        private CodeMapService _mapService = null;
        private Dictionary<string, string> CountryCodes = null;

        public PageApplyPassportInfo()
        {
            InitializeComponent();
            SetProcessBase(ProcessApplyPassportInfo.Instance);
        }

        private bool ReadQWDConfig()
        {
            CountryReader config = new CountryReader();
            if (!config.OnReading())
            {
                MsgBox.Show(config.Error);
                return false;
            }
            CountryCodes = config.CountryCodes;        
            return true;
        }

        private void InitCodeMapService()
        {
            _mapService = CodeMapService.Instance;
            if (!_mapService.Inited)
            {
                _mapService.LoadConfig();
            }
            ReadQWDConfig();
        }

        //初始化窗体数据
        public override void InitCtrls()
        {
            InitKeyboards();
            base.InitCtrls();
            GetControls();
            InitCodeMapService();          
        }

        private void GetControls()
        {
            textBoxQWD = GetControl<TextBox>("textBoxQWD") as TextBox;
            textBoxCJSY = GetControl<TextBox>("textBoxCJSY") as TextBox;
            textBoxYXQ = GetControl<TextBox>("textBoxYXQ") as TextBox;
            textBoxHZHM = GetControl<TextBox>("textBoxHZHM") as TextBox;
            textBoxCYM = GetControl<TextBox>("textBoxCYM") as TextBox;
            textBoxXM = GetControl<TextBox>("textBoxXM") as TextBox;
            textBoxCCHZHM = GetControl<TextBox>("textBoxCCHZHM") as TextBox;
            kCheckBoxJZ = GetControl<KCheckBox>("kCheckBoxJZ") as KCheckBox;
            kCheckBoxHZSXCXSQ = GetControl<KCheckBox>("kCheckBoxHZSXCXSQ") as KCheckBox;
            kCheckBoxHZSCSQ = GetControl<KCheckBox>("kCheckBoxHZSCSQ") as KCheckBox;
            kCheckBoxHZHF = GetControl<KCheckBox>("kCheckBoxHZHF") as KCheckBox;
            kCheckBoxHZBF = GetControl<KCheckBox>("kCheckBoxHZBF") as KCheckBox;
            GetHZSQLBCheckBoxs();
            buttonCancell = GetControl<Button>("buttonCancell") as Button;
            SetButtonDefaultStyles(buttonCancell);
            buttonOK = GetControl<Button>("buttonOK") as Button;
            SetButtonDefaultStyles(buttonOK);
        }

        //初始化窗体数据
        public override void InitData()
        {
            base.InitData();
            _bInited = false;
            _appInfo = Process.GetValue<PreApplyInfo>("PreApplyInfo");
            if (_appInfo == null)
            {
                _appInfo = new PreApplyInfo();
            }
            InitTextBoxs();
            InitCheckBoxs();
            _bInited = true;         
        }

        protected void InitCheckBoxs()
        {
            if(string.IsNullOrEmpty(_appInfo.HZSQ.YWLB.Code))
            {
                _appInfo.HZSQ.YWLB.Code = CheckBZLBCode();
            }
            int index = listHZSQLBCheckBoxs.FindIndex(r => _appInfo.HZSQ.YWLB.Code == (string)r.Tag);
            if (index < 0)
            {
                index = 0;
            }
            for (int i = 0; i < listHZSQLBCheckBoxs.Count; i++)
            {
                listHZSQLBCheckBoxs[i].Checked = (i == index);
            }
        }

        protected void InitTextBoxs()
        {
            if (_appInfo == null)
            {
                return;
            }
            if (!string.IsNullOrEmpty(_appInfo.HZSQ.QWD.Value))
            {
                textBoxQWD.Text = _appInfo.HZSQ.QWD.Value;
            }
            if (!string.IsNullOrEmpty(_appInfo.HZSQ.SQSY.Value))
            {
                textBoxCJSY.Text = _appInfo.HZSQ.SQSY.Value;
            }
            if (!string.IsNullOrEmpty(_appInfo.HZSQ.ZJHM))
            {
                textBoxHZHM.Text = _appInfo.HZSQ.ZJHM;
                //kCheckBoxHZSCSQ.Visible = false;
            }
            if (!string.IsNullOrEmpty(_appInfo.HZSQ.ZJYXQZ))
            {
                textBoxYXQ.Text = _appInfo.HZSQ.ZJYXQZ;
            }
            List <LabellextApplyInfo> listJZInfo = _appInfo.HZSQ.HZJZ;
            for(int i = 0; i< listJZInfo.Count; i++)
            {
                LabellextApplyInfo info = listJZInfo[i];
                if(string.IsNullOrEmpty(info.JZZL.Code))
                {
                    continue;
                }
                if("1A" == info.JZZL.Code) //曾持护照号码加注
                {
                    textBoxCCHZHM.Text = info.JZNR;
                }
                else if ("11" == info.JZZL.Code) // 姓名加注
                {
                    textBoxXM.Text = info.JZNR;
                }
                else if ("19" == info.JZZL.Code) // 曾用名加注
                {
                    textBoxCYM.Text = info.JZNR;
                }
            }
        }

        private string CheckBZLBCode()
        {
            if (string.IsNullOrEmpty(_appInfo.HZSQ.ZJYXQZ))
            {
                return "11";  // 首次申领
            }

            string zjyqx = _appInfo.HZSQ.ZJYXQZ;

            string dateNow = DateTime.Now.ToString("yyyyMMdd");

            // 还没有过期
            if (dateNow.CompareTo(zjyqx) < 0)
            {
                return "21";
            }
            else // 过期重领
            {
                return "13";
            }
        }

        private void GetHZSQLBCheckBoxs()
        {
            List<Control> list = dicRootGroup["groupYWLB"];
            foreach(Control ctl in list)
            {
                if(ctl is KCheckBox)
                {
                    listHZSQLBCheckBoxs.Add(ctl as KCheckBox);
                }
            }
        }

        private bool CheckUserCheckedIsOK()
        {
            if(string.IsNullOrEmpty(textBoxCJSY.Text) || string.IsNullOrEmpty(textBoxQWD.Text))
            {
                MsgBox.Show("前填写前往地和出境事由.");
                return false;
            }           
            int count = 0;
            foreach(KCheckBox box in listHZSQLBCheckBoxs)
            {
                if(box.Checked)
                {
                    count++;
                }
            }
            if (count == 0)
            {
                MsgBox.Show("没有选择办证类别.");
                return false;
            }
            else if(count > 1)
            {
                MsgBox.Show("系统错误: 选择了多个办证类别.");
                return false;
            }

            if (kCheckBoxHZBF.Checked
              || kCheckBoxHZSXCXSQ.Checked
              || kCheckBoxHZHF.Checked)
            {
                if (string.IsNullOrEmpty(textBoxHZHM.Text)
                    || string.IsNullOrEmpty(textBoxYXQ.Text))
                {
                    MsgBox.Show("请填写历史证件信息.");
                    return false;
                }
            }

            string todayDate = DateTime.Now.ToString("yyyyMMdd");
            string yxq = textBoxYXQ.Text;
            if (kCheckBoxHZSXCXSQ.Checked)
            {
                if (yxq.CompareTo(todayDate) > 0)
                {
                    MsgBox.Show("您的证件在有效期内，不能办理过期申领，请选择补发！");
                    return false;
                }
            }
            if (kCheckBoxHZBF.Checked)
            {
                if (yxq.CompareTo(todayDate) < 0)
                {
                    MsgBox.Show("您的证件不在有效期内，不能办理补发，请选择过期申领！");
                    return false;
                }
            }

            if (kCheckBoxJZ.Checked)
            {
                if(string.IsNullOrEmpty(textBoxCCHZHM.Text)
                    && string.IsNullOrEmpty(textBoxCYM.Text)
                    && string.IsNullOrEmpty(textBoxXM.Text))
                {
                    MsgBox.Show("加注内容不能为空!");
                    return false;
                }
            }

            if(kCheckBoxHZSCSQ.Checked && !string.IsNullOrEmpty(_appInfo.HZSQ.ZJHM))
            {
                MsgBox.Show("已经办理过护照，不能选择首次申请!");
                return false;
            }
            return true;
        }

        private void UpdateQWDInfo()
        {
            string cjsy = textBoxCJSY.Text;
            string cjsy_code = _mapService.FindCode("CJSY", cjsy);
            string qwd = textBoxQWD.Text;
            if(CountryCodes.ContainsKey(qwd))
            {
                string qwd_code = CountryCodes[qwd];
                _appInfo.HZSQ.QWD = new CodeMap(qwd_code, qwd);
            }
            else
            {
                string error = $"[{qwd}]的国家代码不存在! ";
                Log.WriteAsync(error);
                MsgBox.Show(error);
            }       
            _appInfo.HZSQ.SQSY = new CodeMap(cjsy_code, cjsy);
        }

        private void UpdateBZLBInfo()
        {
            foreach (KCheckBox box in listHZSQLBCheckBoxs)
            {
                if (box.Checked)
                {
                    _appInfo.HZSQ.YWLB.Code = (string)box.Tag;
                    _appInfo.HZSQ.YWLB.Value = box.Title;
                    break;
                }
            }         
            if(_appInfo.HZSQ.YWLB.Code != "11")
            {
                _appInfo.HZSQ.ZJHM = textBoxHZHM.Text;
                _appInfo.HZSQ.ZJYXQZ = textBoxYXQ.Text;
            }
        }

        /// <summary>
        /// 更新护照加注信息
        /// </summary>
        private void UpdateHZJZInfo()
        {
            if (!kCheckBoxJZ.Checked)
            {
                _appInfo.HZSQ.SFJZ.Code = "0";
                _appInfo.HZSQ.SFJZ.Value = "不需要";
                _appInfo.HZSQ.HZJZ.Clear();
                return;
            }
            _appInfo.HZSQ.SFJZ.Code = "1";
            _appInfo.HZSQ.SFJZ.Value = "需要";
            _appInfo.HZSQ.HZJZ.Clear();
            if (!string.IsNullOrEmpty(textBoxCYM.Text))
            {
                LabellextApplyInfo info = new LabellextApplyInfo();
                info.JZZL.Code = "19";
                info.JZZL.Value = "曾用名加注";
                info.JZNR = textBoxCYM.Text;
                _appInfo.HZSQ.HZJZ.Add(info);
            }
            if (!string.IsNullOrEmpty(textBoxCCHZHM.Text))
            {
                LabellextApplyInfo info = new LabellextApplyInfo();
                info.JZZL.Code = "1A";
                info.JZZL.Value = "曾持照加注";
                info.JZNR = textBoxCCHZHM.Text;
                _appInfo.HZSQ.HZJZ.Add(info);
            }
            if (!string.IsNullOrEmpty(textBoxXM.Text))
            {
                LabellextApplyInfo info = new LabellextApplyInfo();
                info.JZZL.Code = "11";
                info.JZZL.Value = "姓名加注";
                info.JZNR = textBoxXM.Text;
                _appInfo.HZSQ.HZJZ.Add(info);
            }
        }

        /// <summary>
        /// 保存窗体数据(窗体本次做完后, 进入下一步之前)
        /// </summary>
        public override void UpdateData()
        {
            UpdateBZLBInfo();
            UpdateHZJZInfo();
            UpdateQWDInfo();
            Process.SetValue("HZChecked", true);
            Process.SetValue("PreApplyInfo", _appInfo);
        }

        /// <summary>
        /// 清理窗体数据(窗体本次做完后)
        /// </summary>
        public override void ClearData()
        {
            base.ClearData();
            _appInfo = null;
            for (int i = 0; i < listHZSQLBCheckBoxs.Count; i++)
            {
                listHZSQLBCheckBoxs[i].Checked =false;
            }
            kCheckBoxJZ.Checked = false;
        }

        /// <summary>
        /// 窗体关闭时
        /// </summary>
        public override void Close()
        {
            base.Close();
        }

        public override void StartWork()
        {
            base.StartWork();
        }

        public override void StopWork()
        {
            base.StopWork();
        }

        public override void OnCountdownCompleted(object sender, EventArgs e)
        {
            Log.WriteAsync("用户操作超时，返回首页");
            base.OnCountdownCompleted(sender, e);
        }

        protected override void btnBack_Click(object sender, EventArgs e)
        {
            base.btnBack_Click(sender, e);
        }

        protected override void btnNext_Click(object sender, EventArgs e)
        {            
            if(!CheckUserCheckedIsOK())
            {
                return;
            }
            StopCountdown();
            UpdateData();
            ClearData();
            Process.ToAny("YSLPages.PageSelectDocumentType");
        }

        protected override void btnCancel_Click(object sender, EventArgs e)
        {
            base.btnCancel_Click(sender, e);
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            StopCountdown();
            if (!CheckUserCheckedIsOK())
            {
                return;
            }
            UpdateData();
            ClearData();
            Process.ToAny("YSLPages.PageSelectDocumentType");
        }

        private void btnCancell_Click(object sender, EventArgs e)
        {
            StopCountdown();
            Process.SetValue("HZChecked", false);
            if(_appInfo != null)
            {
                _appInfo.HZSQ.Reset();
            }
            ClearData();
            Process.ToAny("YSLPages.PageSelectDocumentType");
        }

        protected override void DefWndProc(ref System.Windows.Forms.Message m)
        {
            switch (m.Msg)
            {
                case (int)MessageType.WM_COPYDATA:
                    OnKeyBoardMsgReceived(m);
                    break;
                default:
                    base.DefWndProc(ref m);
                    break;
            }
        }
    }
}
